<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link https://swoft.org
 * @document https://swoft.org/docs
 * @contact group@swoft.org
 * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Http\Controller;

use App\Models\OrdersDetail;
use App\Models\OrdersMain;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Server\Annotation\Mapping\RequestMethod;
use Swoft\Validator\Annotation\Mapping\Validate;
use Swoft\Redis\Redis;

// use Swoft\Http\Message\Response;

/**
 * Class OrdersController
 *
 * @Controller(prefix="/orders")
 * @package App\Http\Controller
 */
class OrdersController
{
    /**
     * Get data list. access uri path: /orders
     * @RequestMapping(route="/orders", method=RequestMethod::GET)
     */
    public function index(): array
    {
        $id = 12;
        Redis::set('user:profile:' . $id, "Swoft");

        $userDesc = Redis::get('user:profile:' . $id);
        var_dump($userDesc);

        // redis 连接池的使用
        $redis = Redis::connection('redis.pool2');
        $redis->get('name');

        return ['item0', 'item1'];
    }

    /**
     * Get one by ID. access uri path: /orders/{id}
     * @RequestMapping(route="{id}", method=RequestMethod::GET)
     * @return array
     */
    public function get(): array
    {
        return ['item0'];
    }

    /**
     * Create a new record. access uri path: /orders
     * @Validate(validator="orders")
     * @RequestMapping(route="/orders", method=RequestMethod::POST)
     */
    public function post()
    {
        /** @var OrdersMain $ordersPost */
        $ordersPost=jsonForObject(OrdersMain::class);//包含了主订单和子订单数据
        $orderNo=date('Ymd').
            substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13),
                1))), 0, 8);
        $orderDetail_array=mapToModelsArrary($ordersPost->getOrderItems(),
            OrdersDetail::class,[],true);//true参数 代表返回是一个数组，字段和数据库一致
        if($ordersPost){
            $ordersPost->fill(["order_no"=>$orderNo,"create_time"=>date('Y-m-d h:i:s')]);

            tx(function () use($ordersPost,$orderDetail_array,$orderNo){
                if($ordersPost->save() &&   OrdersDetail::insert($orderDetail_array))
                    return OrderCreateSuccess($orderNo);
                throw new \Exception("创建订单失败");
            },$result);

            return $result;

        }
        return OrderCreateFail();
    }

    /**
     * Update one by ID. access uri path: /orders/{id}
     * @RequestMapping(route="{id}", method=RequestMethod::PUT)
     * @return array
     */
    public function put(): array
    {
        return ['id' => 1];
    }

    /**
     * Delete one by ID. access uri path: /orders/{id}
     * @RequestMapping(route="{id}", method=RequestMethod::DELETE)
     * @return array
     */
    public function del(): array
    {
        return ['id' => 1];
    }
}
